package com.longrise.bjjt.camera;

import java.io.ByteArrayOutputStream;
import java.io.File;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.longrise.LEAP.Base.Remote.Utils;
import com.longrise.bjjt.util.FileUtils;
import com.longrise.bjjt.util.StringUtils;
import com.longrise.bjjt.util.UiUtil;
import com.longrise.bjjt_lib.R;

@SuppressLint("HandlerLeak")
@SuppressWarnings("deprecation")
public class SurfaceViewCameraActivity extends Activity implements OnTouchListener, OnClickListener
{

	public int resultCode = 110;
	boolean flashFlag = true;
	private float focusX;
	private float focusY;
	private Bitmap focus_bitmap;

	private RelativeLayout fl_sv;// 显示对焦图片和提示图片的根布局
	private ImageView imageBox;// 对焦图片
	private ImageView iv_flash;// 闪光灯图片
	private ImageView iv_frame;// 拍照中间提示图片
	private ImageView iv_photo;// 拍照按钮
	private Camera mCamera;// 照相机
	private SurfaceHolder mHolder;

	private int midX;
	private int midY;

	private SurfaceView sv_camera;// 相机界面
	private ImageView tv_return;// 返回按钮
	private TextView tv_title;// 提示拍照主题
	
	private TextView tv_title_bottom;//标题下面提示

	private Bundle mBundle;

	private int id;
	
	private String title;//标题
	
	private String titleBottom;//标题下面下提示
	
	private int backGroundResourceId; //背景图片id
	

	Handler mHandler = new Handler()
	{
		public void handleMessage(android.os.Message msg)
		{
			switch (msg.what)
			{
			case 1:
				if (imageBox != null)
				{ // 隐藏对焦图片
					imageBox.setAlpha(0.0F);
					if (fl_sv != null)
					{
						fl_sv.removeView(imageBox);
					}
				}
				break;

			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		// getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
		// WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.custome_camera_layout);
		initView();
		initdata();

	}

	/**
	 * 初始化数据界面
	 */

	private void initdata()
	{
		Intent localIntent = getIntent();
		if (localIntent != null)
		{
			mBundle = localIntent.getExtras();
			title = mBundle.getString("title");//顶部标题
			titleBottom = mBundle.getString("titleBottom");//标题下小提示
			backGroundResourceId = mBundle.getInt("backGroundResourceId", 0);//图片资源
			
			if(StringUtils.isEmpty(title)) {
				title = "";
			}
			
			if(StringUtils.isEmpty(titleBottom)) {
				titleBottom = "";
			}
			
			tv_title.setText(title);
			tv_title_bottom.setText(titleBottom);
			
			if(backGroundResourceId != 0) {
				iv_frame.setVisibility(View.VISIBLE);
				iv_frame.setImageResource(backGroundResourceId);
			} else {
				iv_frame.setVisibility(View.GONE);
			}
			
		}
	}

	private void initView()
	{
		WindowManager localWindowManager = (WindowManager) getApplication().getSystemService("window");
		DisplayMetrics localDisplayMetrics = new DisplayMetrics();

		localWindowManager.getDefaultDisplay().getMetrics(localDisplayMetrics);
		this.setMidX((localDisplayMetrics.widthPixels / 2));
		this.setMidY((localDisplayMetrics.heightPixels / 2));

		this.fl_sv = ((RelativeLayout) findViewById(R.id.fl_sv));
		this.tv_title = ((TextView) findViewById(R.id.tv_title));
		this.tv_title_bottom = ((TextView) findViewById(R.id.tv_title_bottom));
		this.iv_frame = ((ImageView) findViewById(R.id.iv_frame));
		this.iv_photo = ((ImageView) findViewById(R.id.iv_photo));
		this.iv_flash = ((ImageView) findViewById(R.id.iv_flash));
		this.tv_return = ((ImageView) findViewById(R.id.tv_return));
		this.sv_camera = ((SurfaceView) findViewById(R.id.sv_camera));
		fl_sv.setOnTouchListener(this);
		this.iv_photo.setOnClickListener(this);
		this.iv_flash.setOnClickListener(this);
		this.tv_return.setOnClickListener(this);

		this.mHolder = this.sv_camera.getHolder();
		this.mHolder.addCallback(new SurfaceHolder.Callback()
		{

			@Override
			public void surfaceDestroyed(SurfaceHolder holder)
			{
				releasecamera();
			}

			@Override
			public void surfaceCreated(SurfaceHolder holder)
			{
				try
				{
					mCamera = Camera.open();
					if (mCamera == null)
					{ // 提示用户打开权限
						showAlertDialog("无法获取系统相机功能，请检查是否开启摄像头权限");
						return;

					}
					initCamera();
				} catch (Exception e)
				{
					e.printStackTrace();
					showAlertDialog("无法获取系统相机功能，请检查是否开启摄像头权限");
				}

			}

			@Override
			public void surfaceChanged(SurfaceHolder holder, int format, int width, int height)
			{
				CameraAutoForcus();
			}
		});
		mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
	}

	/**
	 * 初始化摄像头参数，并展开预览界面
	 */
	@SuppressLint("InlinedApi")
	protected void initCamera()
	{
		try
		{
			if (null != mCamera)
			{
				// 获取相机的参数
				Parameters param = mCamera.getParameters();
				// param.setPreviewSize(640, 480); // 预览尺寸,注意要在摄像头支持的范围内选择
				param.setPictureSize(640, 480); // 照片尺寸,注意要在摄像头支持的范围内选择
				param.setJpegQuality(100); // 设置相片质量
				param.setPictureFormat(PixelFormat.JPEG);
				param.setFlashMode(Parameters.FLASH_MODE_OFF);
				if (param.getSupportedFocusModes().contains(Parameters.FOCUS_MODE_AUTO))
				{
					param.setFocusMode(Parameters.FOCUS_MODE_AUTO);// FOCUS_MODE_CONTINUOUS_PICTURE

				}
				mCamera.setParameters(param); // 设置相机参数
				mCamera.setPreviewDisplay(mHolder);
				mCamera.startPreview();// 打开预览界面
				if (mCamera != null)
				{
					mCamera.cancelAutoFocus();

				}
			}

		} catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	@SuppressLint("ClickableViewAccessibility")
	@Override
	public boolean onTouch(View v, MotionEvent event)
	{
		if (mCamera == null)
		{
			return false;

		}

		switch (event.getAction())
		{
		case MotionEvent.ACTION_DOWN:
			focusX = event.getX();
			focusY = event.getY();
			startFocus(focusX, focusY);
			break;

		}

		return true;
	}

	/**
	 * 对焦显示图片效果
	 * 
	 * @param focusX2
	 * @param focusY2
	 */
	private void startFocus(float focusX2, float focusY2)
	{
		if (this.imageBox != null)
		{
			this.fl_sv.removeView(this.imageBox);
			this.imageBox = null;
		}
		this.imageBox = new ImageView(this);
		// 获取对焦的模型图片Bitmap
		this.focus_bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.touch_focus);
		this.imageBox.setImageBitmap(this.focus_bitmap);
		this.imageBox.setAlpha(0.0F);
		this.imageBox.setX(focusX2 - this.focus_bitmap.getWidth() / 2);
		this.imageBox.setY(focusY2 - this.focus_bitmap.getHeight() / 2);
		this.imageBox.setAlpha(1.0F);
		this.fl_sv.addView(this.imageBox);
		CameraAutoForcus();// 点击对焦一下
		mHandler.sendEmptyMessageDelayed(1, 2000);
	}

	@Override
	public void onClick(View v)
	{
		int id = v.getId();
		if (id == R.id.iv_photo)
		{
			// 停止预览
			TakeAndSavePicture();
		} else if (id == R.id.iv_flash)
		{
			try
			{
				if (flashFlag)
				{
					if (null != mCamera)
					{
						iv_flash.setSelected(true);
						Parameters parameters = mCamera.getParameters();
						parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
						mCamera.setParameters(parameters);
						flashFlag = false;
					}
				} else
				{
					iv_flash.setSelected(false);
					if (null != mCamera)
					{
						Parameters parameters = mCamera.getParameters();
						parameters.setFlashMode(Parameters.FLASH_MODE_OFF);
						mCamera.setParameters(parameters);
					}
					flashFlag = true;
				}
			} catch (Exception e)
			{
				e.printStackTrace();
				UiUtil.showToast(SurfaceViewCameraActivity.this, "对不起没有获取到您设备的闪光灯，请直接拍照");
			}
		} else if (id == R.id.tv_return)
		{
			SurfaceViewCameraActivity.this.finish();
		}

	}

	/**
	 * 保存图片信息
	 */
	private void TakeAndSavePicture()
	{
		// 隐藏焦点图片
		if (this.imageBox != null)
		{
			this.imageBox.setAlpha(0.0F);
			if (this.fl_sv != null)
			{
				this.fl_sv.removeView(this.imageBox);
			}
		}

		if (this.mCamera == null)
		{ // 若相机为null跳出
			return;
		}

		// 开始拍照，并返回拍照信息
		mCamera.takePicture(new ShutterCallback()
		{

			@Override
			public void onShutter()
			{

			}
		}, null, new MyPictureCallBack());

	}

	/**
	 * 提示用户打开摄像头权限
	 * 
	 * @param string
	 */
	protected void showAlertDialog(String string)
	{
		Builder builder = new Builder(this);
		builder.setTitle("提示");
		builder.setMessage(string);
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener()
		{

			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				finish();
			}
		});
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener()// 跳转设置界面
		{

			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				Intent intent = new Intent(Settings.ACTION_SETTINGS);// 跳转设置界面
				startActivity(intent);
				finish();
			}
		});
		builder.setCancelable(false);
		builder.create();
		builder.show();
	}

	/**
	 * 自动对焦
	 */
	private void CameraAutoForcus()
	{
		if (null != mCamera)
		{
			mCamera.autoFocus(new AutoFocusCallback()
			{

				@Override
				public void onAutoFocus(boolean success, Camera camera)
				{
					if (success)
					{
						if (mCamera != null)
						{
							mCamera.cancelAutoFocus();
						}

					}
				}
			});
		}
	}

	// 相片拍摄完成时调用
	class MyPictureCallBack implements PictureCallback
	{

		@Override
		public void onPictureTaken(byte[] data, Camera camera)
		{
			SavePicturetoSdcard(data);
			sendImage(data);
			mCamera.startPreview();// 拍完照后重新开始预览
		}

	}

	// 保存相片到sdcard
	public boolean SavePicturetoSdcard(byte[] data)
	{
		boolean success = false;
		try
		{
			if ((data != null) && (!data.equals("")) && (data.length > 0))
			{
				String dir = FileUtils.getDir("KCKP", this);
				File file = new File(dir, FileUtils.dateformaterfilename());

				boolean writeFileissuccess = FileUtils.writeFile(data, file.getAbsolutePath(), false);// 将文件写入到SD卡下
				success = writeFileissuccess;
				return success;
			}
		} catch (Exception e)
		{
			e.printStackTrace();
			UiUtil.showToast(SurfaceViewCameraActivity.this, "照片拍摄出错请重新拍此张照片");
			success = false;
		}
		return success;
	}

	/**
	 * 当销毁时 释放资源
	 */
	private void releasecamera()
	{

		if (mCamera != null)
		{
			mCamera.release();
			mCamera = null;
			System.gc();

		}
	}

	@Override
	protected void onDestroy()
	{
		super.onDestroy();
		if (this.focus_bitmap != null)
		{
			this.focus_bitmap.recycle();
			this.focus_bitmap = null;
		}
		if (this.iv_frame != null)
		{
			this.iv_frame = null;
		}
		if (this.mCamera != null)
		{
			releasecamera();
			this.mCamera = null;
		}

		System.gc();

	}

	@Override
	public void onBackPressed()
	{
		SurfaceViewCameraActivity.this.finish();

		super.onBackPressed();

	}

	// 由于图片的质量过高，无法回传数据，现在需要在这里处理图片然后上传
	private byte[] minData(byte[] data)
	{
		// 将data转换成bitmap，缩小bitmap的尺寸，然后再次转为data上传
		Bitmap oldimgeBitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
		Bitmap imgeBitmap = bitmapNewWaH(oldimgeBitmap);// 获取新的bitmap
		// 将新的bitmap转为data
		byte[] bitmaptoBytes = BitmaptoBytes(imgeBitmap);
		return bitmaptoBytes;
	}

	public void sendImage(byte[] data)
	{
		// byte[] data1=minData(data);//将data压缩以便传输
		Intent intent = new Intent();
		Bundle b = new Bundle();
		b.putByteArray("image", data);
		b.putInt("id", id);
		intent.putExtras(b);
		this.setResult(SurfaceViewCameraActivity.RESULT_OK, intent);
		this.finish();
	}

	public int getMidX()
	{
		return midX;
	}

	public void setMidX(int midX)
	{
		this.midX = midX;
	}

	public int getMidY()
	{
		return midY;
	}

	public void setMidY(int midY)
	{
		this.midY = midY;
	}

	// 获取bitmap的宽高，将宽度设为640，高度以倍数缩小，然后设置到bitmap中
	private Bitmap bitmapNewWaH(Bitmap imgeBitmap2)
	{
		int oldWidth = imgeBitmap2.getWidth();
		int oldHeight = imgeBitmap2.getHeight();
		// 获取新的宽高
		int times = oldWidth / 640;
		int width = 640;
		int height = oldHeight / times;
		// 计算缩放比例
		// 计算缩放比例
		float scaleWidth = ((float) width) / oldWidth;
		float scaleHeight = ((float) height) / oldHeight;
		// 想要缩放的宽高
		Matrix matrix = new Matrix();
		matrix.postScale(scaleWidth, scaleHeight);
		Bitmap newbitmap = Bitmap.createBitmap(imgeBitmap2, 0, 0, oldWidth, oldHeight, matrix, true);
		Log.e("test", newbitmap.getWidth() + ":" + newbitmap.getHeight());
		return newbitmap;
	}

	// bitmap转byte[]
	private byte[] BitmaptoBytes(Bitmap bm)
	{
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
		return baos.toByteArray();
	}
}
